package com.financial.service.platbalancepay.service.impl;

import com.financial.service.platbalancepay.dao.GybalanceWechatagencyReceiptDao;
import com.financial.service.platbalancepay.domain.GybalanceWechatagencyReceiptDO;
import com.financial.service.platbalancepay.service.BalanceAgencyPayService;
import com.financial.service.platbalancepay.utils.JsonUtils;
import com.financial.service.platbalancepay.utils.apiresult.ApiResult;
import com.financial.service.platbalancepay.connector.PlatformPayFegin;
import com.financial.service.platbalancepay.connector.YspayFegin;
import com.financial.service.platbalancepay.constants.FinancialPayConfigEnumConstants;
import com.financial.service.platbalancepay.constants.FinancialReceiptBalancepayEnumConstants;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.Map;

/**
 * describe:
 *
 * @author zhaopengjun
 * @date 2019/8/30 10:47
 */
@Service
public class BalanceAgencyPayServiceImpl implements BalanceAgencyPayService {
    @Autowired
    private YspayFegin yspayFegin;
    @Autowired
    private PlatformPayFegin platformPayFegin;
    @Autowired
    private GybalanceWechatagencyReceiptDao gybalanceWechatagencyReceiptDao;
    public static final Logger logger = LoggerFactory.getLogger(BalanceAgencyPayServiceImpl.class);

    @Override
    public Map<String, Object> ysAgencyPay(Map<String, Object> requestMap) {
        logger.info("金融中心余额代付请求银盛代付接口参数", JsonUtils.objectToJson(requestMap));
        Map<String, Object> map = null;
        String outTradeNo = requestMap.get("outTradeNo").toString();
        String payAmount = requestMap.get("balancePaymentAmount").toString();
        String subject = requestMap.get("subject").toString();
        String bankName = requestMap.get("bankName").toString();
        String bankCity = requestMap.get("bankCity").toString();
        String bankAccountName = requestMap.get("bankAccountName").toString();
        String bankCardType = requestMap.get("bankCardType").toString();
        String bankAccountType = requestMap.get("bankAccountType").toString();
        String bankAccountNo = requestMap.get("bankAccountNo").toString();
        String platfromMarking = requestMap.get("platfromMarking").toString();
        String payType = requestMap.get("payType").toString();
        //获取tooken
        int platfromId = platformPayFegin.getPlatfromId(platfromMarking);
        int channelsId = platformPayFegin.getChannelsId(payType);
        // todo后续添加回执保存
        if (StringUtils.isEmpty(outTradeNo) || StringUtils.isEmpty(payAmount)
                || StringUtils.isEmpty(bankAccountNo)
                || StringUtils.isEmpty(subject) ||
                StringUtils.isEmpty(bankName) || StringUtils.isEmpty(bankCity)
                || StringUtils.isEmpty(bankAccountName) || StringUtils.isEmpty(bankCardType)
                || StringUtils.isEmpty(bankAccountType)) {
            return ApiResult.paramIsNull();
        }
        requestMap.put("platfromId", String.valueOf(platfromId));
        requestMap.put("channelsId", String.valueOf(channelsId));
        requestMap.put("platfromMarking", platfromMarking);
        //"01"代表余额代付
        requestMap.put("payment_type", payType);
        try {
            map = yspayFegin.transferAccounts(requestMap);
            logger.info("调用银盛回执信息" + JsonUtils.objectToJson(map));
            if (null != map) {
                map.put("outTradeNo", outTradeNo);
                map.put("platfromId", platfromId);
                map.put("subject", subject);
                saveReceipt(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("out_trade_no:{},余额代付请求银盛失败:{}", outTradeNo, e.getMessage());
        }
        return map;
    }

    @Override
    public Map<String, Object> paymentQuery(Map<String, Object> requestMap) {
        logger.info("接收优店financial主动查询金融中心余额代付参数"+JsonUtils.objectToJson(requestMap));
        Object temp = null;
        temp = requestMap.get("out_trade_no");
        String outTradeNo = temp != null ?temp.toString():null;
        temp = requestMap.get("shopdate");
        String shopdate = temp != null ?temp.toString():null;
        temp = requestMap.get("platfromMarking");
        String platfromMarking = temp != null ?temp.toString():null;
        temp = requestMap.get("payType");
        String payType = temp != null ?temp.toString():null;
        if(StringUtils.isEmpty(outTradeNo)||StringUtils.isEmpty(shopdate)
                ||StringUtils.isEmpty(platfromMarking)||StringUtils.isEmpty(payType)){
            return ApiResult.paramIsNull();
        }
        //根据平台标识获取id
        int platfromId = platformPayFegin.getPlatfromId(platfromMarking);
        //根据支付通道获取id
        int channelsId = platformPayFegin.getChannelsId(payType);
        requestMap.put("platfromId",String.valueOf(platfromId));
        requestMap.put("channelsId",String.valueOf(channelsId));
        Map<String, Object> resultMap = null;
        try {
            resultMap = yspayFegin.paymentQuery(requestMap);
            logger.info("金融中心主动查询余额代付调用银盛结果集"+JsonUtils.objectToJson(resultMap));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("金融中心主动查询余额代付调用银盛失败:{}",e.getMessage());
        }
        return resultMap;
    }

    private void saveReceipt(Map<String, Object> map) {
        logger.info("金融中心余额代付记录保存"+JsonUtils.objectToJson(map));
        String outTradeNo = "";
        GybalanceWechatagencyReceiptDO gybalanceWechatagencyReceiptDO = new GybalanceWechatagencyReceiptDO();
        try{
            String code = map.get("code").toString();
            String subject = map.get("subject").toString();
            outTradeNo = map.get("outTradeNo").toString();
            String platfromId = map.get("platfromId").toString();

            if (code.equals("10000")) {
                //保存余额代付回执信息
                String msg = map.get("msg").toString();
                String tradeStatus = map.get("trade_status").toString();
                gybalanceWechatagencyReceiptDO.setCode(code);
                gybalanceWechatagencyReceiptDO.setMsg(msg);
                gybalanceWechatagencyReceiptDO.setSubject(subject);
                gybalanceWechatagencyReceiptDO.setGmtCreate(new Date());
                gybalanceWechatagencyReceiptDO.setGmtModified(new Date());
                gybalanceWechatagencyReceiptDO.setIsDelete(FinancialPayConfigEnumConstants.ENUM_ISDELETE_UNDEL);
                gybalanceWechatagencyReceiptDO.setOutTradeNo(map.get("out_trade_no").toString());
                gybalanceWechatagencyReceiptDO.setPlatfromappid(platfromId);
                gybalanceWechatagencyReceiptDO.setResponseType(FinancialReceiptBalancepayEnumConstants.ENUM_RESPONSETYPE_SYNC);
                gybalanceWechatagencyReceiptDO.setTradeStatus(tradeStatus);
                gybalanceWechatagencyReceiptDO.setTotalAmount(new BigDecimal(map.get("total_amount").toString()).setScale(2, RoundingMode.HALF_UP));
                gybalanceWechatagencyReceiptDao.save(gybalanceWechatagencyReceiptDO);
            } else {
                String subMsg = map.get("sub_msg").toString();
                gybalanceWechatagencyReceiptDO.setCode(code);
                gybalanceWechatagencyReceiptDO.setMsg(subMsg);
                gybalanceWechatagencyReceiptDO.setSubject(subject);
                gybalanceWechatagencyReceiptDO.setGmtCreate(new Date());
                gybalanceWechatagencyReceiptDO.setGmtModified(new Date());
                gybalanceWechatagencyReceiptDO.setIsDelete(FinancialPayConfigEnumConstants.ENUM_ISDELETE_UNDEL);
                gybalanceWechatagencyReceiptDO.setOutTradeNo(outTradeNo);
                gybalanceWechatagencyReceiptDO.setPlatfromappid(platfromId);
                gybalanceWechatagencyReceiptDO.setResponseType(FinancialReceiptBalancepayEnumConstants.ENUM_RESPONSETYPE_SYNC);
                gybalanceWechatagencyReceiptDO.setTradeStatus("TRADE_ACCEPT_FAIL");
                gybalanceWechatagencyReceiptDao.save(gybalanceWechatagencyReceiptDO);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("订单号outTradeNo:{},余额代付保存失败:{}",outTradeNo,e.getMessage());
        }


    }
}